package com.bigtotoro.shuiyincamera.image;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.adapter.CommonAdapter;
import com.bigtotoro.shuiyincamera.adapter.ViewHolder;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.editimage.task.StickerTask;
import com.bigtotoro.shuiyincamera.editimage.utils.BitmapUtils;
import com.bigtotoro.shuiyincamera.editimage.utils.Matrix3;
import com.bigtotoro.shuiyincamera.editimage.view.StickerItem;
import com.bigtotoro.shuiyincamera.editimage.view.StickerView;
import com.bigtotoro.shuiyincamera.editimage.view.TextStickerView;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouch;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouchBase;
import com.bigtotoro.shuiyincamera.view.SelectPictureActivity;
import com.bigtotoro.shuiyincamera.util.FileUtils;
import com.bigtotoro.shuiyincamera.view.SquareImageView;
import com.luck.picture.lib.entity.LocalMedia;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 批量添加水印
 */
public class MountAdd02Activity extends BaseActivity implements View.OnClickListener, TextWatcher {
    private int imageWidth, imageHeight;//
    private LinearLayout model_content;

    /**
     * 1.获取图片集合
     * 2.合成图片
     * 3.保存
     **/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkInitImageLoader();//检测图片载入框架是否初始化
        setContentView(R.layout.activity_mount_add02);

        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels / 2;
        imageHeight = metrics.heightPixels / 2;

        getData();
        initView();
        initGrid();  //初始化贴图列表
        initData("stickers");
    }

    //    public static String filePath;// 需要编辑图片路径
    public String saveFilePath;// 图片保存路径
    private List<LocalMedia> paths; //接收到的图片集合
    private List<String> imgPaths = new ArrayList<>();//接收到图片的压缩路径集合
    public List<Bitmap> bitmap_list = new ArrayList<>();  //执行保存任务的bitmap集合

    private void getData() {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels;
        imageHeight = metrics.heightPixels;

        paths = (List<LocalMedia>) getIntent().getSerializableExtra("path");//图片集合
        if (paths != null && paths.size() > 0) {
            for (int i = 0; i < paths.size(); i++) {
//                imgPaths.add(paths.get(i).getCompressPath());//  获取压缩路径
                String newPath = paths.get(i).getCompressPath();
                Bitmap bitmap = BitmapUtils.getSampledBitmap(newPath, imageWidth,
                        imageHeight);
                bitmap_list.add(bitmap);
            }
        }

        File outputFile = FileUtils.genEditFile();  //图片的保存路径
        saveFilePath = outputFile.getAbsolutePath();

        LoadImageTask task = new LoadImageTask();
        task.execute(paths.get(0).getCompressPath());
    }

    /**
     * 编辑图片
     */
    private Bitmap mainBitmap;  //操作完成后获得的图片
    public ImageViewTouch mainImage; // 底部图层，放原始照片这一层
    private View backBtn;

    public StickerView mStickerView;// 贴图层画板
    public TextStickerView mTextStickerView;//文本贴图层画板
    public StickerView mImageStickerView;//图片水印模式画板

    private void initView() {
        findViewById(R.id.btn_tietu).setOnClickListener(this);
        findViewById(R.id.btn_close).setOnClickListener(this);
        findViewById(R.id.btn_text).setOnClickListener(this);
        findViewById(R.id.btn_image).setOnClickListener(this);
        findViewById(R.id.btn_submit).setOnClickListener(this);
        model_content = findViewById(R.id.model_content);
        model_content.setVisibility(View.GONE);
        visibelMode = 1;


        mainImage = findViewById(R.id.main_image);// 页面正中的图片显示控件
        backBtn = findViewById(R.id.back_btn);// 左上角退出按钮
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                model_content.setVisibility(View.GONE);
                visibelMode = 1;

                onBackPressed();
            }
        });

        /**
         * 真正操作图片的画布，都只存放在editImageActivity中
         * */
        mStickerView = (StickerView) findViewById(R.id.sticker_panel); //添加图片表情的画布
        mImageStickerView = (StickerView) findViewById(R.id.sticker_add_image); //添加图片表情的画布
        mTextStickerView = (TextStickerView) findViewById(R.id.text_sticker_panel);//添加文字画布
    }

    private List<String> pathList = new ArrayList<String>();// 图片路径列表

    private void initData(String folderPath) {  //获取assets中的图片，放入列表
        pathList.clear();
        try {
            String[] files = getAssets().list(folderPath);
            for (String name : files) {
                if (name.lastIndexOf(".") > 0) {
                    pathList.add(folderPath + File.separator + name);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        commonAdapter.notifyDataSetChanged();
    }

    private List<String> mPhotoList = new ArrayList<>();
    private List<String> mSelectData = new ArrayList<>();
    private GridView grid;
    private CommonAdapter<String> commonAdapter;

    private void initGrid() {
        final DisplayImageOptions imageOption = new DisplayImageOptions.Builder()
                .cacheInMemory(true).showImageOnLoading(R.drawable.yd_image_tx)
                .build();// 下载图片显示
        grid = findViewById(R.id.grid);
        commonAdapter = new CommonAdapter<String>(this,
                pathList,
                R.layout.item_grid_item) {
            @Override
            public void convert(ViewHolder holder, String s) {
                SquareImageView iv_photo = holder.getConvertView().findViewById(R.id.iv_photo);
                ImageLoader.getInstance().displayImage("assets://" + s,
                        iv_photo, imageOption);
                //选中改变
                View item = holder.getConvertView().findViewById(R.id.item);
                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = (int) v.getTag();
                        String path = pathList.get(position);
                        //选中的贴图添加到贴图画布上，可以重复选中同一个
                        mStickerView.addBitImage(FileUtils.getImageFromAssetsFile(MountAdd02Activity.this, path));
                    }
                });
                item.setTag(holder.getPosition());
            }
        };
        grid.setAdapter(commonAdapter);
    }

    /**
     * 异步载入编辑图片
     */
    private LoadImageTask mLoadImageTask;

    public void loadImage(String filepath) {
        if (mLoadImageTask != null) {
            mLoadImageTask.cancel(true);
        }
        mLoadImageTask = new LoadImageTask();
        mLoadImageTask.execute(filepath);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String text = s.toString().trim();
        mTextStickerView.setText(text);//文字输入完成后，直接在画布上设置
    }


    /**
     * 导入文件图片任务
     * 为什么要搞一个异步载入图片，将图片转换成bitmap
     * 因为画布操作要用到bitmap?
     * 因为涉及到生成bitmap
     * 最后让mainbitmap == 生成的bitmap,各个子fragment可以直接调用
     * 这一步省不了。
     */
    private final class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {  //设置显示在界面正中的图片的宽高，params[0]是图片路径
            Bitmap bitmap = BitmapUtils.getSampledBitmap(params[0], imageWidth,
                    imageHeight);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) { //参数是AsyncTask的第三个参数
            //将获得的bitmap存储起来
            //限定选中了多张图片时，存储bitmap
            //result为空。。。

            changeMainBitmap(result, false);
        }
    }

    /**
     * @param newBit
     * @param needPushUndoStack
     */
    public void changeMainBitmap(Bitmap newBit, boolean needPushUndoStack) { //第二个参数是是否将图片压栈
        if (newBit == null)  //如果获取到的图片为空，返回
            return;
        if (mainBitmap == null || mainBitmap != newBit) {  //如果获取到的图片为空，返回
            mainBitmap = newBit;
            mainImage.setImageBitmap(mainBitmap);
            mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        }
    }

    private SaveStickersTask mSaveTask;

    private void save() {
        if (mSaveTask != null) {
            mSaveTask.cancel(true);
        }
        //循环任务
        for (int i = 0; i < bitmap_list.size(); i++) {
            //循环任务
            mSaveTask = new SaveStickersTask(this);
            mSaveTask.execute(bitmap_list.get(i));//调用execute方法时传入AsynTask的第一个参数
        }
    }

    /**
     * 保存贴图任务,三个保存方法合在一个方法里保存贴图数据
     */
    private final class SaveStickersTask extends StickerTask {
        public SaveStickersTask(Activity activity) {
            super(activity);
        }

        @Override
        protected Bitmap doInBackground(Bitmap... bitmaps) {
            // System.out.println("保存贴图!");
            // 先把mainBitmap复制了一份到resultBit中
            //用canvas设置这个resultBit的bitmap作为背景画布，将文字绘制在上面
            Matrix touchMatrix = mainImage.getImageViewMatrix(); //touchMatrix是不变的
            Bitmap resultBit = Bitmap.createBitmap(bitmaps[0]).copy(
                    Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(resultBit);//画布是根据传入的bitmap生成的画布

            float[] data = new float[9];
            //将mainImage的矩阵数据复制到data数组中
            touchMatrix.getValues(data); // 底部图片变化记录矩阵原始数据
            Matrix3 cal = new Matrix3(data); // 辅助矩阵计算类
            Matrix3 inverseMatrix = cal.inverseMatrix(); // 计算逆矩阵
            Matrix m = new Matrix();
            m.setValues(inverseMatrix.getValues());

            int width = resultBit.getWidth();
            int height = resultBit.getHeight();

            /**两个方法分开执行，互不干扰**/
            handleImage2(canvas, m, width, height); //根据传入的bitmap生成的画布，根据mainImage计算出的矩阵
            handleImage(canvas, m); //根据传入的bitmap生成的画布，根据mainImage计算出的矩阵
            return resultBit;
        }

        /**
         * @param canvas //根据传入的bitmap生成的画布
         * @param m      //根据mainImage计算出的矩阵
         */
        @Override
        public void handleImage(Canvas canvas, Matrix m) { // 添加的图片水印
            /**
             * 保存贴图
             * **/
            LinkedHashMap<Integer, StickerItem> addItems02 = mStickerView.getBank();
            for (Integer id : addItems02.keySet()) {
                StickerItem item = addItems02.get(id);
//                item.matrix.postConcat(m); //乘以底部图片变化矩阵
                canvas.drawBitmap(item.bitmap, item.matrix, null);
            }

            /**
             * 保存文字
             * **/
            float[] f = new float[9];
            m.getValues(f);
            int dx = (int) f[Matrix.MTRANS_X];
            int dy = (int) f[Matrix.MTRANS_Y];
            float scale_x = f[Matrix.MSCALE_X];
            float scale_y = f[Matrix.MSCALE_Y];
            canvas.save();
            canvas.translate(dx, dy);
            canvas.scale(scale_x, scale_y);
            //在文字画布上绘制文字图形
            //我需要的也正是文字画布,在每一张bitmap上使用文字画布合成一次图片，就是批量合成
            mTextStickerView.drawText(canvas, mTextStickerView.layout_x,
                    mTextStickerView.layout_y, mTextStickerView.mScale, mTextStickerView.mRotateAngle);
            canvas.restore(); //将文字绘制在了画布上

            /*
             * 保存图片水印
             */
            LinkedHashMap<Integer, StickerItem> addItems = mImageStickerView.getBank();// 获取每层贴图数据
            //拿到了所有的添加的图片水印
            for (Integer id : addItems.keySet()) {
                StickerItem item = addItems.get(id);
//                item.matrix.postConcat(m);// 乘以底部图片变化矩阵,(贴图会逐渐往边缘移动)
//                item.matrix.preConcat(m);// 乘以底部图片变化矩阵,(贴图会逐渐变大)
                // postConcat相当于后乘，即 a=b×a
                //preConCat(b)相当于前乘,即 a=a×b
                canvas.drawBitmap(item.bitmap, item.matrix, null);
                //将水印图片保存到原图片中，每次获取到的都是最后刚刚添加的这个图片水印
            }
        }

        @Override
        public void handleImage2(Canvas canvas, Matrix m, int width, int height) {
        }

        @Override
        public void onPostResult(Bitmap result) {
            //将生成的bitmap保存在集合中
            //直接在这里将图片保存到内存中，不用到EditImageActivity中保存
            //图片存储真实路径
            String realPath = BitmapUtils.writeImage(result, saveFilePath, 100);
            Toast.makeText(MountAdd02Activity.this, "图片保存在" + saveFilePath.toString(),
                    Toast.LENGTH_SHORT).show();
//            mRealPaths.add(realPath); //保存到litepal时需要用到真实地址
            MyArt art = new MyArt();
            art.setHeight(imageHeight);
            art.setWidth(imageWidth);
            art.setCreate_time(System.currentTimeMillis() + "");
            art.setPath(realPath);
            art.setType(0);
            art.save();
            taskDoneCount++;
            if (taskDoneCount == bitmap_list.size()) {
                //跳转到查看我的作品页面，点击查看我的作品跳转作品列表
                Intent intent = new Intent(MountAdd02Activity.this, ShowMyArtsActivity.class);
                intent.putExtra(EXTRA_OUTPUT, realPath);
                intent.putExtra("create_time", art.getTrueCreateTime());
                intent.putExtra("width", imageHeight);
                intent.putExtra("height", imageWidth);
                intent.putExtra("type", "0");

                startActivity(intent);
                finish();
            }


//            mTextStickerView.clearTextContent();
//            mTextStickerView.resetView();
//            mTextStickerView.setVisibility(View.GONE);
//
//            mImageStickerView.clear();   //暂时不清空画布---2019/4/19
//            mImageStickerView.setVisibility(View.GONE);

            changeMainBitmap(result, true);
        }
    }

    public List<String> mRealPaths = new ArrayList<>();


    public static final String FILE_PATH = "file_path";
    public static final String EXTRA_OUTPUT = "extra_output";

    private void initStickerView() {
        mStickerView = findViewById(R.id.sticker_panel);
        mStickerView.setVisibility(View.VISIBLE);
    }

    private void initTextStickerView() {
        mTextStickerView = findViewById(R.id.text_sticker_panel);
        mTextStickerView.setVisibility(View.VISIBLE);
        mTextStickerView.setTextColor(getResources().getColor(R.color.font_3));
    }

    private void initImageStickerView() {
        mImageStickerView = findViewById(R.id.sticker_add_image);
        mImageStickerView.setVisibility(View.VISIBLE);
    }

    /**
     * 从相册选择编辑图片
     */
    private void selectFromAblum() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            openAblumWithPermissionsCheck();
        } else {
            openAblum();
        }
    }

    public static final int REQUEST_PERMISSON_SORAGE = 1;
    public static final int SELECT_GALLERY_IMAGE_CODE = 7;
    public static final int ACTION_REQUEST_EDITIMAGE = 9;

    private void openAblum() {
        startActivityForResult(new Intent(
                        this, SelectPictureActivity.class),
                SELECT_GALLERY_IMAGE_CODE);
    }

    private void openAblumWithPermissionsCheck() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_PERMISSON_SORAGE);
            return;
        }
        openAblum();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSON_SORAGE
                && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openAblum();
            return;
        }
    }

    private String mContent, mColor;
    int mAlpha;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SELECT_GALLERY_IMAGE_CODE://相册返回
                    handleSelectFromAblum(data);
                    break;
                case REQUEST_CODE_SETTING_TEXT://设置字体返回
                    mContent = data.getStringExtra("content");
                    mColor = data.getStringExtra("color");
                    mAlpha = data.getIntExtra("alpha", 0);
                    String h = Integer.toHexString(mAlpha);
                    if (h.length() < 2) { //不足两位前面补0
                        h = "0" + h;
                    }
                    mTextStickerView.setText(mContent);
                    mTextStickerView.setTextColor(Color.parseColor("#" + h + mColor));
//                    mTextStickerView.getBackground().setAlpha(Integer.valueOf(mAlpha));
                    break;
            }
        }
    }

    private String path;

    private void handleSelectFromAblum(Intent data) {
        String filepath = data.getStringExtra("imgPath");
        path = filepath;
        /**
         * 拿到图片路径后，怎么将图片加载到mStickerView画布上？
         */
        Bitmap bitmap = BitmapUtils.getSampledBitmap(path, 200, 200);
        mImageStickerView.addBitImage(bitmap);//将从相册选取的图片加载到画布上
    }

    private static final int REQUEST_CODE_SETTING_TEXT = 3001;
    private int visibelMode = 0;//0已显示1未显示
    private int taskDoneCount = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_tietu://表情水印
                if (visibelMode == 0) {  //
                    model_content.setVisibility(View.GONE);
                    visibelMode = 1;
                } else if (visibelMode == 1) {
                    model_content.setVisibility(View.VISIBLE);
                    visibelMode = 0;
                }
                initStickerView();
                break;
            case R.id.btn_text://文字水印
                model_content.setVisibility(View.GONE);
                visibelMode = 1;

                initTextStickerView();
                startActivityForResult(new Intent(MountAdd02Activity.this, SettingTextActivity.class)
                        , REQUEST_CODE_SETTING_TEXT);
                break;
            case R.id.btn_image://图片水印
                model_content.setVisibility(View.GONE);
                visibelMode = 1;

                initImageStickerView();
                selectFromAblum();  //选择输入图片，点击进入相册
                break;
            case R.id.btn_close://关闭表情水印
                model_content.setVisibility(View.GONE);
                visibelMode = 1;
                break;
            case R.id.btn_submit://保存
                taskDoneCount = 0;
                model_content.setVisibility(View.GONE);
                visibelMode = 1;
                save();
                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MountAdd02Activity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MountAdd02Activity");//统计页面
        MobclickAgent.onPause(this);
    }


}
